package org.bitmap.mm.util;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

 final class FileLove {
	
	public static String hashKeyForDisk(String keystr) {
		if(keystr==null)return "";
		String cacheKey;
		String urlkey  = keystr.replaceAll(" ", "");
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
			mDigest.update(urlkey.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(urlkey.hashCode());
		}

		return cacheKey;
	}
	
	public static final long getUsableSpace(File path) {
		final StatFs stats = new StatFs(path.getPath());
		return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
	}

	public static final File getExternalCacheDir(Context context) {

		File f = new File(Environment.getExternalStorageDirectory()
				+ File.separator + "Android");
		if (!f.exists()) {
			f.mkdir();
		}
		f = new File(Environment.getExternalStorageDirectory() + File.separator
				+ "Android" + File.separator + "data");
		if (!f.exists()) {
			f.mkdir();
		}
		final String cacheDirString = "/Android/data/"
				+ context.getPackageName() + "/cache/";
		f = new File(Environment.getExternalStorageDirectory() + cacheDirString);
		if (!f.exists()) {
			f.mkdir();
		}
		return f;
	}
	
	public static final boolean isText(String str){
		if(str==null||str.equals("")){
			return false;
		}
		return true;
	}

	public static final String bytesToHexString(byte[] bytes) {
		// http://stackoverflow.com/questions/332079
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}
}
